package models

import (
	"fmt"
	"github.com/astaxie/beego/orm"
	_ "github.com/go-sql-driver/mysql"
)

//新闻
type News struct {
	Id    int
	Title string
	Url   string
}

func init() {
	orm.RegisterModel(new(News))
}
func (this News) ToString() string {
	return fmt.Sprintf("Id:%d\tTitle:%s\tUrl:%s\tAge:%d\tisActive:%v", this.Id, this.Title, this.Url)
}

//添加新闻
func CreateNews(n News) {

	fmt.Println(n)
	newsList := []News{
		News{Title: n.Title, Url: n.Url},
	}
	o := orm.NewOrm()
	if successNums, err := o.InsertMulti(len(newsList), newsList); err != nil {
		fmt.Println("insert fail.....")
	} else {
		fmt.Println("success inserted %d datas", successNums)
	}
}

//获取所有新闻列表
func ListNews() []News {
	var newsList []News
	orm.NewOrm().QueryTable("news").All(&newsList)
	return newsList
}

//get user count
func CountNews() {
	cnt, _ := orm.NewOrm().QueryTable("news").Count()
	fmt.Println("******get user count******")
	fmt.Println("All user count:", cnt)
}

//get the only one user
func GetNews() {
	var n News
	err := orm.NewOrm().QueryTable("news").Filter("Id", 5).One(&n)
	if err == nil {
		fmt.Println("******get only one user******")
		fmt.Println(n.ToString())
	}
}

//get the only one user
func GetNewsList() {
	var newsList []News
	_, err := orm.NewOrm().QueryTable("news").Filter("name__contains", "awd").All(&newsList)
	if err == nil {
		for _, n := range newsList {
			fmt.Println("******get only one user******")
			fmt.Println(n.ToString())
		}
	}
}

//get limit user
func LimitUser() {
	var newsList []News
	_, err := orm.NewOrm().QueryTable("news").Limit(6).OrderBy("-Name").All(&newsList)
	if err == nil {
		for _, n := range newsList {
			fmt.Println("******get limit user******")
			fmt.Println(n.ToString())
		}
	}
}

//get user limit,offset
func LimitoffsetUser() {
	var newsList []News
	_, err := orm.NewOrm().QueryTable("news").Limit(12, 4).OrderBy("Id").All(&newsList)
	if err == nil {
		for _, n := range newsList {
			fmt.Println("******get limit user offer******")
			fmt.Println(n.ToString())
		}
	}
}

//del user
func DelNews() {
	num, err := orm.NewOrm().QueryTable("news").Filter("Id", "5").Delete()
	fmt.Printf("Affected Num: %s, %s", num, err)
}

//update user
func UpdateNews() {
	num, err := orm.NewOrm().QueryTable("news").Filter("name__contains", "awd").Update(orm.Params{
		"name": "#########",
	})
	fmt.Printf("Affected Num: %s, %s", num, err)
}
